(function($) {
    function showInputError(input, error) {
        var $input = $(input),
            $formGroup = $input.parent('.form-group'),
            $error;

        if (!$formGroup.hasClass('has-error')) {
            $error = $('<span class="help-block error">' + error + '</span>');
            $formGroup.addClass('has-error');
            $input.after($error);
            $input.one('focus', function() {
                $formGroup.removeClass('has-error');
                $error.remove();
            });
        }
    }

    $(document).on('click', '.member .invite-link', function(e) {
        var $parent = $(this).parent('.member'),
            token = $parent.attr('id').split('-')[1],
            name = $parent.find('.name').html(),
            href = window.location.protocol + window.location.host + '/teams/join/' + token;
        YH.alert('<p>如果 ' + name + ' 收不到邀请邮件，你可以把下面的邀请地址发给他：<br>' + href + '</p>', '查看邀请链接');
        e.preventDefault();
    }).on('click', '.member .delete', function(e) {
        var $parent = $(this).parent('.member'),
            token = $parent.attr('id').split('-')[1],
            name = $parent.find('.name').html(),
            modal = YH.confirm('<p>不再邀请 ' + name + ' 加入团队了吗？</p>', '删除邀请', function () {
                $.ajax({
                    url: '/teams/invitations/' + token + '/delete',
                    type: 'post',
                    data: YH.getCsrfToken(),
                    dataType: 'json'
                }).done(function (resp) {
                    if (resp.success) {
                        $parent.hide().remove();
                    }
                }).always(function () {
                    modal.modal('hide');
                });
            });
        e.preventDefault();
    }).on('click', '.member .remove', function(e) {
        var $parent = $(this).parent('.member'),
            shipId = $parent.attr('id').split('-')[1],
            name = $parent.find('.name').html(),
            modal = YH.confirm('<p>确定要从团队中移除 ' + name + ' 吗？</p>', '移除成员', function () {
                $.ajax({
                    url: '/teams/members/' + shipId + '/remove',
                    type: 'post',
                    data: YH.getCsrfToken(),
                    dataType: 'json'
                }).done(function (resp) {
                    if (resp.success) {
                        $parent.hide().remove();
                    }
                }).always(function () {
                    modal.modal('hide');
                });
            });
        e.preventDefault();
    }).on('click', '.member .grade', function(e) {
        var $this = $(this),
            $parent = $this.parent('.member'),
            shipId = $parent.attr('id').split('-')[1],
            action = $this.hasClass('upgrade') ? 'upgrade' : 'downgrade';

        $.ajax({
            url: '/teams/members/' + shipId + '/' + action,
            type: 'post',
            data: YH.getCsrfToken(),
            dataType: 'json'
        }).done(function(resp) {
            if (resp.success) {
                if (action == 'upgrade') {
                    $this.removeClass('upgrade').addClass('downgrade').attr({
                        title: '降级为普通成员'
                    }).html('成员');
                    $parent.find('.label').html('管理员');
                } else {
                    $this.removeClass('downgrade').addClass('upgrade').attr({
                        title: '升级为管理员'
                    }).html('管理员');
                    $parent.find('.label').html('成员');
                }
            }
        });
        e.preventDefault()
    });

    $(document).ready(function() {
        var $members = $('#team_members'),
            memberTemplate = YH.template('member');

        $('#btn-invite').on('click', function (e) {
            var $form = $(this.form),
                $emails = $form.find('textarea[name=emails]'),
                defVal = $(this).html(),
                $this = $(this);

            if (!$.trim($emails.val())) {
                return false;
            }

            $this.html('正在邀请...').prop('disabled', true);

            $.ajax({
                url: $form.attr('action'),
                type: 'post',
                data: $form.serialize(),
                dataType: 'json'
            }).done(function (resp) {
                if (resp.success) {
                    _.each(resp.data, function(model) {
                        model.avatar = '/static/images/avatar.jpg';
                        model.name = model.email.split('@')[0];
                        $members.append(memberTemplate(model));
                    });
                    $emails.val('');
                    $form.parents('.modal').modal('hide');
                } else {
                    showInputError($emails, resp.message);
                }
            }).always(function () {
                $this.html(defVal).prop('disabled', false);
            });

            e.preventDefault();
        });
    })
})(jQuery);
